<template>
  <div class="viewcontainer">
    <el-dialog :title="detailTitle" :visible.sync="addVisible" width="552px" :close-on-click-modal="false">
      <datadetail ref="editForm" v-model="addData"></datadetail>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogSave">确定</el-button>
      </span>
    </el-dialog>

    <el-container style="height: 100%">
      <el-aside width="300px">
        <el-tree
          @node-drop="nodeDropFinish"
          :highlight-current="true"
          :default-expanded-keys="[-1]"
          :allow-drag="allowdrag"
          :allow-drop="allowdrop"
          :props="treeProps"
          node-key="FID"
          @node-click="nodeClick"
          ref="tree"
          draggable
          :expand-on-click-node="false"
          :load="query"
          lazy
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span class="custom-tree-node-cmd" v-if="data.FID != '-1'">
              <i
                class="el-icon-circle-plus-outline"
                title="添加子节点"
                v-if="isAllowAdd(node)"
                @click="showAddForm(3, node)"
              ></i>
              <i
                class="el-icon-edit"
                title="编辑节点"
                @click="showEditForm(3, node)"
              ></i>
              <i
                class="el-icon-circle-close"
                title="删除"
                @click="remove(data, node)"
                v-if="data.FPID != '-1'"
              ></i>
              <i
                class="el-icon-refresh"
                title="刷新"
                @click="refresh(node)"
                v-if="!data.FLEAF"
              ></i>
            </span>
          </span>
        </el-tree>
      </el-aside>
      <el-main class="shelvesMain">
          <querylist ref="querylist" :value="currShelves"></querylist>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import datadetail from "./detail";
import querylist from "./querylist";
import { dataHelper, utils } from "hi-ui";
import baseView from "@/views/base";

export default {
  name: "basicdata",
  extends: baseView,
  components: {
    datadetail,
    querylist,
  },
  data() {
    return {
      addVisible: false,
      modleFilePath: "shelves/dataset/ShelvesEntity.xml",
      loading: false,
      addData: {},
      editData: {},
      editstate: "add",
      detailTitle: null,
      addParentNode: null,
      currShelves:{
        desc:null,
        id:null,
        isStore:null,
      },
      treeProps: {
        label: "FDESC",
        isLeaf: (data, node) => {
          return data.FLEAF ? true : false;
        },
      },
    };
  },
  model: {
    prop: "value",
    event: "valuechange",
  },
  props: {
    value: {
      type: Object,
    },
  },

  computed: {},
  watch: {},
  methods: {
    test() {
      debugger;
    },
    //拖拽完成
    nodeDropFinish(draggingNode, dropNode, dropType, ev) {
      let parent = dropNode;
      if (dropType != "inner") parent = dropNode.parent;

      let oldData = Object.assign({}, draggingNode.data);
      draggingNode.data.FPATH = parent.data.FPATH + draggingNode.data.FID + "/";
      draggingNode.data.FPID = parent.data.FID;
      draggingNode.data.FSORT = 9999;
      let saveHelper = this.createSaveHelper(
        this.modleFilePath,
        this.$route.path
      );

      saveHelper.update(oldData, draggingNode.data);
      let children = parent.childNodes;
      for (let i = 0; i < children.length; i++) {
        let child = children[i];
        // let childData = Object.assign({}, child.data);
        // childData.FSORT = i + 1;
        saveHelper.update(child.data, {
          FSORT: i + 1,
        });
      }
      saveHelper.save().then((res) => {
        this.refresh(parent);
      });
    },
    //是否允许拖拽
    allowdrag(node) {
      return node.data.FPID != "-1";
    },
    //是否允许拽入
    allowdrop(draggingNode, dropNode, type) {
      if (dropNode.level == 1) return false;

      if (this.isAllowAdd(dropNode)) return true;
      return false;
    },
    //刷新
    refresh(node) {
      node.loaded = false;
      node.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
    },
    //是事允许添加子级
    isAllowAdd(node) {
      let rootNode,_rootNode,currLevel = 0;
      rootNode= _rootNode= node;
      console.log(node)
      while (_rootNode.data.FPID&&_rootNode.data.FPID != "-1") {
        _rootNode = _rootNode.parent;
        currLevel++;
      }
      if (rootNode.data.FLEVEL === 0) return true;
      //let currLevel = node.FPATH.split('/') - 2;
      let dataLevel = rootNode.data.FLEVEL || 1;
      if (rootNode.data.FLEVEL > currLevel) return true;
      return false;
    },
    //leave=>1:根，2：兄弟，3、子级
    showAddForm(leave, node) {
      let tree = this.$refs.tree,
        ID = utils.string.guid();
      node = node || tree.currentNode.node;
      this.editstate = "add";
      this.detailTitle="新增货架";
      this.addData = {
        FID: ID,
        FPID: -1,
        FPATH: "/" + ID + "/",
        FPDESC: "根",
        FVALUE: null,
        FNOTE: null,
      };

      if (leave == 2) {
        if (!tree.currentNode) {
          this.$message({
            message: "请选中一个节点",
            type: "error",
          });
          return;
        }
        if (!node.parent.data) {
          this.$message({
            message: "找不到父节点",
            type: "error",
          });
          return;
        }
        this.addParentNode = node.parent;
        this.addData.FPID = node.parent.data.FID;
        this.addData.FPATH = node.parent.data.FPATH + this.addData.FID + "/";
        this.addData.FPDESC = node.parent.data.FDESC;
      } else if (leave == 3) {
        this.addParentNode = node;
        this.addData.FPID = node.data.FID;
        this.addData.FPDESC = node.data.FDESC;
        this.addData.FPATH = node.data.FPATH + this.addData.FID + "/";
        this.addData.FLEVEL=node.data.FLEVEL;
      }
      this.addVisible = true;
    },
    showEditForm(leave, node){
        this.editstate = "edit";
        this.detailTitle="编辑货架:" + node.data.FDESC || "";
        this.queryEntity(
            {
            FID: node.data.FID,
            },
            this.modleFilePath,
            this.$route.path
        ).then((res) => {
            if (res.dataPack.rows.length > 0) {
            this.addData = res.dataPack.rows[0];
            this.addData.FPDESC = node.parent.data?node.parent.data.FDESC:"根";
            this.editData = Object.assign({}, this.addData);
            this.addParentNode = node;
            this.addVisible = true;
            } else
            this.$message({
                message: "没有找到数据",
                type: "error",
            });
        });
    },
    dialogSave(){
        if(this.editstate=="add"){
            this.add();
        }else if(this.editstate=="edit"){
            this.save();
        }
    },
    add() {
      let me = this;
      this.$refs.editForm.validate((valid) => {
        if (!valid) return;
        let saveHelper = this.createSaveHelper(
          this.modleFilePath,
          this.$route.path
        );

        saveHelper.add(this.addData);
        saveHelper.save().then((res) => {
          let tree = me.$refs.tree;
          this.$confirm("保存成功,是否继续添加数据?", "提示", {
            confirmButtonText: "是",
            cancelButtonText: "否",
            type: "success",
          })
            .then(() => {
              this.addData.FID = utils.string.guid();
              this.addData.FDESC = null;
              this.addData.FVALUE = null;
              this.addData.FNOTE = null;
            })
            .catch(() => {
              this.refresh(this.addParentNode);
              // this.addParentNode.loaded = false;
              // this.addParentNode.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
              this.addVisible = false;
            });
        });
      });
    },
    save() {
      let me = this;
      this.$refs.editForm.validate((valid) => {
        if (!valid) return;
        let saveHelper = this.createSaveHelper(
          this.modleFilePath,
          this.$route.path
        );
        saveHelper.update(this.editData,this.addData);
        saveHelper.save().then((res) => {
          let tree = me.$refs.tree;
          tree.currentNode.node.data.FDESC = me.addData.FDESC;
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.refresh(this.addParentNode);
          this.addVisible = false;
        });
      });
    },
    remove(data, node) {
      this.$confirm(`确定要删除【${data.FDESC}】吗`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          let saveHelper = this.createSaveHelper(
            this.modleFilePath,
            this.$route.path
          );
          saveHelper.remove({
            FID: data.FID,
            FPATH: data.FPATH,
          });
          saveHelper.save().then((res) => {
            this.$refs.tree.remove(node);
            this.$message({
              message: "删除成功",
              type: "success",
            });
          });
        })
        .catch(() => {});
    },
    nodeClick(data, node, tree) {
        if(node.data.FID==-1){
          this.currShelves.id=null;
          this.currShelves.desc=null;
        }else{
          this.currShelves.id=node.data.FID;
          this.currShelves.desc=node.data.FDESC;
        }
        //判断当前节点是否是店铺
        if(node.level==2){
          this.currShelves.isStore=true;
        }else{
          this.currShelves.isStore=null;
        }
        console.log(this.currShelves);
    },
    query(node, resolve) {
      let pid = "-1";
      if (node.data) {
        pid = node.data.FID;
      }else if(node.level==0){
        return resolve([{
          FDESC:"全部",
          FID: -1,
        }]);
      }
      this.loading = true;
      let param = new dataHelper.queryHelper.Param();
      let where = new dataHelper.queryHelper.Where();
      where.eq("FPID", pid);
      where.setPage(1, -1);
      param.where = where;
      console.log(param.toStringWithKey());
      this.queryEntity(where, this.modleFilePath, this.$route.path).then(
        (res) => {
          resolve(res.dataPack.rows);
        }
      );
    },
  },
  mounted() {},
};
</script>

<style lang="scss">
.el-aside {
  background: none;
  border-right: 1px solid #304156;
}
.shelvesMain{
    position: relative;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  &:hover .custom-tree-node-cmd {
    display: block;
  }

  .custom-tree-node-cmd {
    display: none;
  }
}
</style>
